﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using JTTD.Common.Helper;
using JTTD.Domain.Dtos.Account;
using JTTD.Domain.IService;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace JTTD.Model
{
    /// <summary>
    /// 自定义用户登录校验    
    /// </summary>
    public class LoginValidator : IResourceOwnerPasswordValidator
    {
        private readonly IUserInfoService _userInfoService;
        public LoginValidator(IUserInfoService userInfoService)
        {
            _userInfoService = userInfoService;
        }

        /// <summary>
        /// 登录用户校验
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {            
            //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
            if (!string.IsNullOrEmpty(context.UserName))
            {
                context.Result = new GrantValidationResult(
                                 subject: context.UserName,
                                 authenticationMethod: "password",
                                 claims: GetUserClaims(context.Password));
            }
            else
            {                
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户信息验证失败！");
            }
        }

        /// <summary>
        /// 可以根据需要设置相应的Claim
        /// </summary>
        /// <returns></returns>
        private Claim[] GetUserClaims(string userType)
        {
            return new Claim[]
            {
                //new Claim("UserId", account.UserId.ToString()),
                //new Claim("OpenId", account.OpenId),
                //new Claim("CompanyUserName", account.CompanyUserName),
                new Claim("type", userType)
            };
        }
    }
}
